package com.upyun;

import java.io.File;
import java.util.HashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.upyun.api.utils.UpYunException;
import com.upyun.api.utils.UpYunUtils;

public class UpYunUploader {
	private static Log logger = LogFactory.getLog(UpYunUploader.class);
	// 回调的方法，见又拍云api
	private String callBackMethod;
	// 回调时调用路径，注意使用绝对路径
	private String callBackUrl;
	// 又拍云的bucket
	private String bucket;
	// 又拍云bucket中的apikey
	private String apiKey;

	public UpYunUploader(String callBackMethod, String callBackUrl,
			String bucket, String apiKey) {
		super();
		this.callBackMethod = callBackMethod;
		this.callBackUrl = callBackUrl;
		this.bucket = bucket;
		this.apiKey = apiKey;
	}

	public UpYunEntity genarateUpyunEntity(String saveFolder)
			throws UpYunException {
		Long lExpiration = ((Long) (System.currentTimeMillis() / 1000 + 1000 * 5 * 10));
		String saveKey = getSaveKey(saveFolder, "{random32}{.suffix}");
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put(callBackMethod, callBackUrl);
		// TODO:DELETE
		logger.info("callBackUrl:" + callBackUrl);
		String policy = UpYunUtils.makePolicy(saveKey, lExpiration, bucket,
				params);
		String signature = getSignature(policy, apiKey);
		return new UpYunEntity(bucket, policy, signature);

	}

	public String getSaveKey(String saveFloder, String pattern) {
		return File.separator + saveFloder + File.separator + pattern;
	}

	public String getSignature(String policy, String API_KEY) {
		return UpYunUtils.signature(policy + "&" + API_KEY);
	}

	public String getBucket() {
		return bucket;
	}

	public void setBucket(String bucket) {
		this.bucket = bucket;
	}

	public String getApiKey() {
		return apiKey;
	}

	public void setApiKey(String apiKey) {
		this.apiKey = apiKey;
	}

	public String getCallBackMethod() {
		return callBackMethod;
	}

	public void setCallBackMethod(String callBackMethod) {
		this.callBackMethod = callBackMethod;
	}

	public String getCallBackUrl() {
		return callBackUrl;
	}

	public void setCallBackUrl(String callBackUrl) {
		this.callBackUrl = callBackUrl;
	}
}
